// 厦门大学计算机专业 | 前华为工程师
// 分享编程技术，没啥深度，但看得懂，适合初学者。
// Java | 安卓 | 前端 | Flutter | iOS | 小程序 | 鸿蒙
// 公众号：蓝不蓝编程


import AlertToast
import SwiftUI
import SDWebImageSwiftUI


struct ConfirmOrderView: View {
    @State var isPresented = false
    @State var orderId = ""
    @StateObject private var viewModel = ConfirmOrderViewModel()
    @State var goods: Goods
    @State private var showToast = false
    var body: some View {
        VStack{
            HStack(){
                WebImage(url: URL(string: goods.squarePic ?? ""))
                    .placeholder{Color.gray}
                    .resizable()
                    .scaledToFit()
                    .frame(width: 100, height: 100)
                VStack(){
                    Text(goods.name).lineLimit(3)
                    Text("￥\(goods.price/100)")
                }
                Spacer()
                Text("×1")
            }.padding()
            VStack(){
                HStack(){
                    Text("商品金额")
                    Spacer()
                    Text("￥\(goods.price/100)")
                }
                HStack(){
                    Text("优惠券")
                    Spacer()
                    Text("无优惠券")
                }
            }.padding()
            Spacer()
            HStack{
                Button(action:{ createOrder()}){
                    Text("提交订单").font(.headline).frame(minWidth: 150)
                }
                .padding(EdgeInsets.init(top: 5, leading: 0, bottom: 5, trailing: 0))
                .foregroundColor(.white)
                .background(Color.main_color)
                .clipShape(RoundedRectangle(cornerRadius: 5))
            }.padding()
        }.toast(isPresenting: $showToast){
            AlertToast(type: .regular, title: "下单成功")
        }
    }
    
    func createOrder() {
        var cartItems:[SimpleCartItem] = []
        
        var simpleCartItem:SimpleCartItem = SimpleCartItem()
        simpleCartItem.goodsId=goods.id
        simpleCartItem.quantity=1
        cartItems.append(simpleCartItem)
        viewModel.createOrder(cartItems:cartItems, callback: {_,orderId,_ in
            self.showToast = true
            self.isPresented = true
        })
    }
}


struct ConfirmOrderView_Previews: PreviewProvider {
    static var previews: some View {
        ConfirmOrderView(goods: Goods())
    }
}
